/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ecom.beans.cart;

import ecom.beans.account.*;
import ecom.beans.dish.*;

import java.util.List;
import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Tian
 */
@Stateful
public class CartSessionBean implements CartSessionRemote {

    @PersistenceContext
    private EntityManager em;

    public int initCart(Long customerId) {

           CartEntity cart = new CartEntity();
		
		em.persist(cart);
		
		cart.setId(customerId);

        em.merge(cart);

        return cart.getId().intValue();

    }

    public boolean updateProduct(ItemEntity item) {
        try {
            em.merge(item);
            return true;
        } catch (Exception e) {
            return false;
        }

    }

    
    public void addProduct(Long cartId, int dishId, int quantity) {

        List<ItemEntity> itemList = getAllCartItems(cartId);

        if (itemList != null && itemList.size() > 0) {

            boolean find = false;

            for (ItemEntity item : itemList) {

                if (item.getItemProduct().getDishId() == dishId) {

                    item.setItemQuantity(quantity + item.getItemQuantity());
                    em.merge(item);
                    find = true;
                    break;
                }

            }

            if (!find) {

                CartEntity cart = (CartEntity) em.createNamedQuery("findCartById").setParameter("id", cartId).getSingleResult();
                DishEntity dish = (DishEntity) em.createNamedQuery("findDishById").setParameter("id", Long.valueOf(dishId)).getSingleResult();

                ItemEntity item = new ItemEntity();

                item.setItemCart(cart);
                item.setItemProduct(dish);
                item.setItemQuantity(quantity);


                em.persist(item);

                cart.setCartTotalPrice(cart.getCartTotalPrice() + (dish.getPrice() * quantity));
                em.merge(cart);

            }

        } else {

            CartEntity cart = (CartEntity) em.createNamedQuery("findCartById").setParameter("id", cartId).getSingleResult();
            DishEntity dish = (DishEntity) em.createNamedQuery("findDishById").setParameter("id", Long.valueOf(dishId)).getSingleResult();

            ItemEntity item = new ItemEntity();

            item.setItemCart(cart);
            item.setItemProduct(dish);
            item.setItemQuantity(quantity);


            em.persist(item);

        }


    }
    

    public void removeProduct(Long cartId, Long dishId) {

    	try {
        ItemEntity item = (ItemEntity) em.createNamedQuery("findItemInCart").setParameter("cartId", cartId).setParameter("productId", dishId).getSingleResult();

        
       	 if (item != null) {
                em.remove(item);
            }
       } catch (Exception e) {
           
       }
    }

    
    public void removeProduct(Long cartId, int productId) {

    	try {
    	
        ItemEntity item = (ItemEntity) em.createNamedQuery("findItemInCart").setParameter("cartId", cartId).setParameter("productId", Long.valueOf(productId)).getSingleResult();
        
        
        
        	 if (item != null) {
                 em.remove(item);
             }
        	 
        } catch (Exception e) {
            
        }
        
        
       
    }
    
    
    public void removeItem(Long itemId) {

    
        ItemEntity item = (ItemEntity) em.createNamedQuery("findItemById").setParameter("id", itemId).getSingleResult();

        
        if (item != null) {
            em.remove(item);
        }
    }

    
    public CartEntity removeCartById(Long cartId) {
        CartEntity cart;
        try {
            cart = this.getCartById(cartId);
            em.remove(cart);

        } catch (Exception e) {
            cart = null;
        }
        return cart;
    }

    public void removeAllItems() {
        List<ItemEntity> itemList = null;

        itemList = em.createNamedQuery("findAllItems").getResultList();
        if (itemList != null) {
            for (ItemEntity item : itemList) {
                em.remove(item);
            }
        }
    }

    public List<ItemEntity> getAllItems() {
        List<ItemEntity> itemList = null;

        itemList = em.createNamedQuery("findAllItems").getResultList();

        return itemList;
    }

    public List<ItemEntity> getAllCartItems(Long cartId) {

        List<ItemEntity> itemList = null;

        itemList = em.createNamedQuery("findAllItemsByCartId").setParameter("cartId", cartId).getResultList();

        return itemList;

    }

    // remplacement du type de retour de booleen a AccountEntity
    public AccountEntity validPayment(Long cartId, String iban) {

        // il faudrait verifier que customerAccount n"est pas null
        AccountEntity customerAccount = (AccountEntity) em.createNamedQuery("findAccountByIBAN").setParameter("accountIBAN", iban).getSingleResult();

        double amount = 0.0;

        amount = getTotalPrice(cartId);
        /*
        if (amount == 0.0) {
        return customerAccount;
        }
         */

        // verifier que withdraw fonctionne
        boolean withdraw = customerAccount.withdraw(amount);
        /*
        if (!withdraw) {
        return customerAccount;
        }
         */
        em.merge(customerAccount);

        List<ItemEntity> itemList = getAllCartItems(cartId);
        for (ItemEntity item : itemList) {

            item.getItemProduct().setQuantity(item.getItemProduct().getQuantity() - item.getItemQuantity());
            em.merge(item.getItemProduct());
            AccountEntity storeAccount = item.getItemProduct().getStore().getStoreAccount();
            storeAccount.deposit(item.getItemProduct().getPrice() * item.getItemQuantity());
            em.merge(storeAccount);
            removeProduct(cartId, item.getItemProduct().getDishId());

        }



        return customerAccount;
    }

    public double getTotalPrice(Long cartId) {

        List<ItemEntity> itemList = getAllCartItems(cartId);
        double totalPrice = 0.0;


        if (itemList == null) {
            return totalPrice;
        }
        for (ItemEntity item : itemList) {

            totalPrice += item.getItemProduct().getPrice() * item.getItemQuantity();

        }


        return totalPrice;
    }

    
    public boolean removeACartById(Long cartId) {
    try {
    removeAllItemsByCartId(cartId);
    CartEntity cart = (CartEntity) em.createNamedQuery("findCartById").setParameter("id", cartId).getSingleResult();
    
    em.remove(cart);
    
    
    } catch (Exception e) {
    
    return false;
    }
    
    return true;
    }
     
    
    public List<CartEntity> removeAllCarts() {

        List<CartEntity> temp = null;

        try {

            temp = (List<CartEntity>) em.createNamedQuery("findAllCarts").getResultList();

            for (int i = 0; i < temp.size(); i++) {

                removeAllItemsByCartId(temp.get(i).getId());
                em.remove(temp.get(i));
            }
        } catch (Exception e) {

            temp = null;
        }

        return temp;
    }

    public boolean removeAllItemsByCartId(Long cartId) {


        List<ItemEntity> itemList = null;

        try {

            itemList = getAllCartItems(cartId);
            if (itemList != null) {
                for (int i = 0; i < itemList.size(); i++) {
                    em.remove(itemList.get(i));
                }
            }
        } catch (Exception e) {

            //itemList = null;
            return false;
        }
        return true;
    }
//alina type boolean->customer

    public CartEntity getCartById(Long id) {

        CartEntity cart = null;

        try {

            cart = (CartEntity) em.createNamedQuery("findCartById").setParameter("id", id).getSingleResult();

        } catch (Exception e) {

            cart = null;
        }

        if (cart != null) {
            return cart;
        } else {
            return cart;
        }
    }
    
    public List<CartEntity> getAllCart(){
    	
    	
    	List<CartEntity> temp = null;

        try {

            temp = (List<CartEntity>) em.createNamedQuery("findAllCarts").getResultList();

           
        } catch (Exception e) {

            temp = null;
        }

        return temp;
    	
    }

}